package org.jazz.web.controller;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jazz.basic.Action;
import org.jazz.basic.ModelAndView;

/**
 * Servlet implementation class FrontController
 */
@WebServlet("*.do")
public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(FrontController.class);
	private static final String PREFIX = "org.jazz.web.controller";
	private static final String APPENDIX = "Controller";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FrontController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			Action action = parsingURI(request.getRequestURI());
			ModelAndView mav = action.execute(request, response);
			logger.info(mav);
			String viewName = mav.getViewName();
			boolean forward = mav.isForward();
			Map<String, Object> dataMap =  mav.getDataMap();
			logger.info(mav.getDataMap());
			Iterator<String> keyIt = dataMap.keySet().iterator();
			
			while(keyIt.hasNext()){
				String key = keyIt.next();
				request.setAttribute(key, dataMap.get(key));
			}
			logger.info(viewName);
			logger.info(forward);
			
			if(forward){
				request.getRequestDispatcher(viewName).forward(request, response);
			}else{
				response.sendRedirect(viewName);
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
	}

	private Action parsingURI(String requestURI) throws Exception {
		logger.info("beforeURI: " + requestURI);
		String url = (requestURI.substring(0,requestURI.lastIndexOf(".")).replaceAll("/", ".")).toUpperCase();
		logger.info("afterURI: " + url);
		String classPath = PREFIX + url + APPENDIX;
		logger.info("classPath: " + classPath);
		Action action = (Action) Class.forName(classPath).newInstance();
		return action;
	}

}
